package org.example.jwt;

import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.Base64Codec;

import java.util.Date;

/**
 * @ClassName : JwtDemo
 * @Description : jwt实例类
 * @Author : tianshuo
 * @Date: 2021-05-27 21:17
 */
public class JwtDemo {

    private final static String sign = "uuid";

    public static void main(String[] args) {
        //test();
        String token = generateToken();
        System.out.println("token信息为：");
        System.out.println(token);
        System.out.println("token的解密信息：");
        for (String s : token.split("\\.")) {
            System.out.println(s);
            System.out.println(Base64Codec.BASE64.decodeToString(s));
        }

//      String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4OCIsInN1YiI6InRpYW5zaHVvIiwiaWF0IjoxNjIyMTIzNDM4LCJleHAiOjE2MjIxMjM0OTh9.Pfv2-HShcBAALeWKgRS0w5lNbl3DRxW4PJ1Q3tiS-hw";
        parseToken(token);

        String customToken = generateCustomToken();
        System.out.println("自定义" + customToken);

        parseCustomToken(customToken);
    }

    /**
     * 生成自定义token
     * @return
     */
    public static String generateCustomToken() {
        JwtBuilder jwtBuilder = Jwts.builder().setId("999")
                .setSubject("tt")
                .setIssuedAt(new Date())
                // 2分钟之后失效
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60))
                .signWith(SignatureAlgorithm.HS256, sign)
                // 自定义参数
                .claim("role", "admin")
                .claim("organId", "999");

        return jwtBuilder.compact();
    }


    /**
     * 解析自定义token
     * @param token
     */
    public static void parseCustomToken(String token) {
        Claims body = Jwts.parser().setSigningKey(sign).parseClaimsJws(token).getBody();
        System.out.println(body.get("role"));
        System.out.println(body.get("organId"));
        System.out.println(body.getId());
    }



    /**
     * 生成jwt
     * @return
     */
    public static String generateToken() {

        JwtBuilder jwtBuilder = Jwts.builder()
                // 声明的标识{"jti":"666"
                .setId("88")
                // 主体，用户{"sub":"tianshuo"}
                .setSubject("tianshuo")
                // iat 创建时间
                .setIssuedAt(new Date())
                // 设置过期时间 ，1分钟之后过期
                .setExpiration(new Date(System.currentTimeMillis()+60*1000))
                //签名手段，参数1：算法，参数 2：盐
                .signWith(SignatureAlgorithm.HS256, sign);

        return jwtBuilder.compact();
    }

    /**
     * 解析验证token
     * 当token设置了失效时间，未失效时，可以直接解析，当token之后，在解析时，会报异常
     * @param token
     */
    public static void parseToken(String token) {

        System.out.println("验证token ,"+token);
        Claims claims = Jwts.parser().setSigningKey(sign).parseClaimsJws(token).getBody();
        System.out.println("id: " + claims.getId());
        System.out.println("sub: " + claims.getSubject());
        System.out.println("iat: " + claims.getIssuedAt());
        System.out.println("exp: "+claims.getExpiration());
    }

}

